package com.lyr.controller;

import com.lyr.pojo.Employee;
import com.lyr.pojo.R;
import com.lyr.pojo.RUtil;
import com.lyr.pojo.User;
import com.lyr.service.EmpService;
import com.lyr.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags ="用户")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private EmpService empService;

    @RequestMapping({"/","/index"})
    public String toLogin(){
        return "index";
    }

    @ApiOperation(value = "登录")
    @GetMapping("/login")
    public R login(String username, String password, Model model, HttpSession session){
            User user = userService.getUserByName(username);
            //用户存在时
            if(user!=null){
                //用户名密码都正确时
                if (password.equals(user.getPassword())){
                    Employee allEmp = empService.getEmpByName(user.getUsername());
                    user.setEmployee(allEmp);
                    session.setAttribute("userInfo",username);
                    return RUtil.success(user);
                }else {
                    //密码不正确时
                    model.addAttribute("msg","用户名或者密码错误");
                    return RUtil.error(500,"用户名或者密码错误");
                }
            }else {
                model.addAttribute("msg","用户名或者密码错误");
                return RUtil.error(500,"用户名或者密码错误");
            }
    }

    @ApiOperation(value = "登出")
    @PostMapping("/logout")
    public String logout(HttpSession session){
        //注销用户
        session.invalidate();
        return "index";
    }
}
